const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

// 中间件
app.use(cookieParser());
app.use(express.json());

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// Routes
app.get('/', (req, res) => {
  res.send('Welcome to Express Server!');
});

app.get('/setCookie', (req, res) => {
  res.cookie('sk', Date.now() + req.host, { domain: 'test.domain.test.com' });
  res.json({
    message: 'This is API endpoint',
    status: 'success',
  });
});

app.get('/getCookie', (req, res) => {
    const skCookie = req.cookies.sk;
    res.json({
        cookie: skCookie || 'Cookie not found'
    });
});

// 404 Error handling
app.use((req, res) => {
  res.status(404).send('404 Not Found');
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(`[${new Date().toISOString()}] Error:`, err);
  res.status(500).json({
    error: 'Internal Server Error',
    message: process.env.NODE_ENV === 'production' ? 'Something went wrong' : err.message
  });
});

// Start server
const PORT = process.env.PORT || 1129;
const server = app.listen(PORT, () => {
  console.log(`[${new Date().toISOString()}] Server is running on http://localhost:${PORT}`);
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing HTTP server');
  server.close(() => {
    console.log('HTTP server closed');
    process.exit(0);
  });
});